/**
 * Java文件解析器
 * 用于解析Java代码中的类、方法、字段等信息
 */
export class JavaFileParser {
  constructor() {
    this.methods = []
    this.classes = []
    this.fields = []
  }

  /**
   * 解析Java代码
   * @param {string} javaCode - Java源代码
   * @returns {Object} 解析结果
   */
  parse(javaCode) {
    this.reset()
    
    const lines = javaCode.split('\n')
    let currentClass = null
    let inComment = false

    lines.forEach((line, index) => {
      const lineNumber = index + 1
      const trimmedLine = line.trim()

      // 跳过空行
      if (!trimmedLine) return

      // 处理多行注释
      if (trimmedLine.startsWith('/*')) {
        inComment = true
        return
      }
      if (trimmedLine.endsWith('*/')) {
        inComment = false
        return
      }
      if (inComment) return

      // 跳过单行注释
      if (trimmedLine.startsWith('//')) return

      // 计算括号数量，用于确定类/方法的范围
      // const bracketCount = 0 // 暂时不需要使用

      // 解析类
      const classMatch = line.match(/^\s*(public|private|protected|static|\s)*\s*class\s+(\w+)/)
      if (classMatch) {
        currentClass = {
          name: classMatch[2],
          line: lineNumber,
          modifier: classMatch[1] ? classMatch[1].trim() : '',
          methods: []
        }
        this.classes.push(currentClass)
        return
      }

      // 解析方法
      const methodMatch = line.match(/^\s*(public|private|protected|static|\s)*[\w<>\]]+\s+(\w+)\s*\([^)]*\)\s*\{?/)
      if (methodMatch && !trimmedLine.startsWith('if') && !trimmedLine.startsWith('for') && !trimmedLine.startsWith('while')) {
        const methodName = methodMatch[2]
        const method = {
          name: methodName,
          line: lineNumber,
          modifier: methodMatch[1] ? methodMatch[1].trim() : '',
          returnType: this.extractReturnType(line),
          parameters: this.extractParameters(line),
          className: currentClass ? currentClass.name : null
        }
        
        this.methods.push(method)
        if (currentClass) {
          currentClass.methods.push(method)
        }
        return
      }

      // 解析字段
      const fieldMatch = line.match(/^\s*(private|public|protected|static|\s)*[\w<>\]]+\s+(\w+)\s*[=;]/)
      if (fieldMatch && !trimmedLine.includes('(')) {
        this.fields.push({
          name: fieldMatch[2],
          line: lineNumber,
          modifier: fieldMatch[1] ? fieldMatch[1].trim() : '',
          type: this.extractFieldType(line)
        })
      }
    })

    return {
      classes: this.classes,
      methods: this.methods,
      fields: this.fields
    }
  }

  /**
   * 提取返回类型
   */
  extractReturnType(line) {
    const match = line.match(/^\s*(public|private|protected|static|\s)*\s*([\w<>\]])+\s+\w+\s*\(/)
    return match ? match[2] : 'void'
  }

  /**
   * 提取参数列表
   */
  extractParameters(line) {
    const match = line.match(/\(([^)]*)\)/)
    if (!match) return []
    
    const paramsStr = match[1].trim()
    if (!paramsStr) return []
    
    return paramsStr.split(',').map(param => {
      const parts = param.trim().split(/\s+/)
      return {
        type: parts[0],
        name: parts[1] || 'param'
      }
    })
  }

  /**
   * 提取字段类型
   */
  extractFieldType(line) {
    const match = line.match(/^\s*(private|public|protected|static|\s)*\s*([\w<>\]])+\s+\w+/)
    return match ? match[2] : 'unknown'
  }

  /**
   * 获取指定行的上下文
   */
  getContext(javaCode, lineNumber, contextLines = 3) {
    const lines = javaCode.split('\n')
    const start = Math.max(0, lineNumber - contextLines - 1)
    const end = Math.min(lines.length, lineNumber + contextLines)
    
    return lines.slice(start, end).join('\n')
  }

  /**
   * 搜索方法
   */
  searchMethods(keyword) {
    return this.methods.filter(method => 
      method.name.toLowerCase().includes(keyword.toLowerCase())
    )
  }

  /**
   * 获取类的所有方法
   */
  getClassMethods(className) {
    return this.methods.filter(method => method.className === className)
  }

  /**
   * 重置解析器状态
   */
  reset() {
    this.methods = []
    this.classes = []
    this.fields = []
  }
}

export default JavaFileParser